package me.zhengjie.controller;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.common.DlaServerConfig;
import me.zhengjie.entity.QueryRecord;
import me.zhengjie.service.QueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static me.zhengjie.util.HistoryUtil.createHistoryResult;

@RestController
public class HistoryController {

    @Resource
    private DlaServerConfig config;
    @Resource
    private QueryService queryService;
    @GetMapping("history")
    @AnonymousAccess
    public Object history(QueryRecord params){
        Map responseBody = new HashMap();
        String dataSource = params.getDataSource();
        List<QueryRecord> queries = queryService.selectAllByParams(params);
        params.setUserName("root");
        List<QueryRecord> userQueries = queryService.selectAllByParams(params);
        responseBody.put("editLabel",userQueries);
        QueryRecord queryRecord = null;
        if (queries.size() > 0) {
            queryRecord = queries.get(0);
            responseBody.put("engine", queryRecord.getEngineName());
        }

        boolean resultVisible;
        if (config.isAllowOtherReadResult(dataSource)) {
            resultVisible = true;
        } else {
            resultVisible = userQueries.size()>0;
        }
        createHistoryResult(responseBody, config.getSelectLimit(), dataSource, queryRecord, resultVisible);
        return responseBody;
    }
}
